﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using iFinity.DNN.Modules.UrlMaster;
using DotNetNuke.ActiveForumsModuleFriendlyUrlProvider.Entities;
namespace DotNetNuke.ActiveForumsModuleFriendlyUrlProvider
{
    public class ActiveForumsModuleProvider : iFinity.DNN.Modules.UrlMaster.ModuleFriendlyUrlProvider
    {
        #region private members
        FriendlyUrlOptions _options = null; //local copy of the Friendly Url Options, which control things like the inclusion of hyphens instead of spaces, etc.
        //the following set of members are specific to this module, and are used to control how the module provider works.
        //these are read from the web.config file, and appear as attributes in the Module Provider declaration
        protected int _noDnnPagePathTabId = -1; //- used to specify if the  module is on a page where the page path should not be included in the url.
        protected string _urlPath;//- specifies the url path to use for a ActiveForums Url

        #endregion

        #region overridden methods and properties
        /// <summary>
        /// Constructor for the ActiveForums Url Provider.  This is called by the Url Master module when loading the Provider
        /// </summary>
        /// <param name="name">Name is supplied from the web.config file, and specifies the unique name of the provider</param>
        /// <param name="attributes">Attributes are the xml attributes from the file</param>
        /// <param name="portalId">The portalId is supplied for the calling portal.  Each instance of the provider is portal specific.</param>
        public ActiveForumsModuleProvider(string name, NameValueCollection attributes, int portalId)
            : base(name, attributes, portalId)
        {
            //look for an attribute specifying which tab the module
            //will not use a page path for.  There can only be one
            //tab specified per portal (because there is no page path, then it
            //can only be a single page, as the way of determining one dnn
            //page from another isn't in the reuqested Url)
            string noDnnPagePathTabRaw = attributes["noDnnPagePathTabId"];
            int.TryParse(noDnnPagePathTabRaw, out _noDnnPagePathTabId);

            _urlPath = attributes["urlPath"];
        }
        /// <summary>
        /// The Change Friendly Url method is called for every Url generated when a page is generated by DotNetNuke.  This call sits 'underneath' the 'NavigateUrl' call in DotNetNuke.
        /// Whenever your module calls NavigateUrl, this method will be also called.  In here, the module developer should modify the friendlyUrlPath to the final state required.
        /// However, because this call is used for all Urls on the page, not just those generated by the target module, some type of high-level filter should be used to make sure only
        /// the module Urls are modified.
        /// 
        /// </summary>
        /// <param name="tab">Current Tab</param>
        /// <param name="friendlyUrlPath">Current Friendly Url Path after going through the Friendly Url Generation process of the Url Master module.</param>
        /// <param name="options">The options currently applying to Urls in this portal (space replacement, max length, etc)</param>
        /// <param name="cultureCode">The culture code being used for this Url (if supplied, may be empty)</param>
        /// <param name="endingPageName">The page name the Url has been called with. Normally default.aspx, but may be different for some modules.</param>
        /// <param name="useDnnPagePath">Out parameter to be set by the module.  If true, the path of the DNN page will be in the Url (ie /pagename).  If false, this part of the Url will be removed. </param>
        /// <param name="messages">List of debug messages.  Add any debug information to this collection to help debug your provider.  This can be seen in the repsonse headers, and also in the 'test Url Rewrite' page in the Url Master module.</param>
        /// <returns></returns>
        public override string ChangeFriendlyUrl(DotNetNuke.Entities.Tabs.TabInfo tab, string friendlyUrlPath, iFinity.DNN.Modules.UrlMaster.FriendlyUrlOptions options, string cultureCode, ref string endingPageName, out bool useDnnPagePath, ref List<string> messages)
        {
            _options = options;//keep local copy of options
            //set default values for out parameters
            useDnnPagePath = true;
            if (messages == null) messages = new List<string>();
            //check if we want to try and modify this Url
            //first check to see if this Url is an 'edit' Url - something that loads a module-specific page.
            //we don't want to mess with these, because they're always permissions based Urls and thus
            //no need to be friendly
            if (Regex.IsMatch(friendlyUrlPath, @"(^|/)(mid|moduleId)/\d+/?", RegexOptions.IgnoreCase) == false)
            {
                Hashtable friendlyUrlIndex = null; //the friendly url index is the lookup we use
                //try and match incoming friendly url path to what we would expect from the module
                //NOTE: regex used here but can be any type of logic to determine if this is a friendly url that applies to the module
                //There will be many different urls created for this tab, so we only want to change the ones we know apply to this module
                //by way of looking for a certain pattern or other unique marker in the Url.
                //For this example, match by looking for 'itemId' - normally the Url would be /pagename/tabid/xx/itemid/yy/default.aspx
                Regex itemUrlRegex = new Regex(@"(?<l>/)?ItemId/(?<itemId>\d+)", RegexOptions.IgnoreCase);
                Match itemUrlMatch = itemUrlRegex.Match(friendlyUrlPath);
                if (itemUrlMatch.Success)
                {

                    //this is a Url we want to modify
                    string rawId = itemUrlMatch.Groups["itemId"].Value;
                    int itemId = 0;
                    if (int.TryParse(rawId, out itemId))
                    {
                        //we have obtained the item Id out of the Url
                        //get the friendlyUrlIndex (it comes from the database via the cache)
                        friendlyUrlIndex = UrlController.GetFriendlyUrlIndex(tab.TabID, tab.PortalID, this, options);
                        if (friendlyUrlIndex != null)
                        {
                            //item urls are indexed with i + itemId ("i5") - this is so we could mix and match entities if necessary
                            string furlkey = "i" + itemId.ToString();  //create the lookup key for the friendly url index
                            string path = (string)friendlyUrlIndex[furlkey];//check if in the index
                            if (path == null)
                            {
                                //don't normally expect to have a no-match with a friendly url path when an itemId was in the Url.
                                //could be a new item that has been created and isn't in the index
                                //do a direct call and find out if it's there
                                path = UrlController.CheckForMissingItemId(itemId, tab.TabID, tab.PortalID, this, options, ref messages);
                            }
                            if (path != null) //got a valid path
                            {
                                //url found in the index for this entry.  So replace the matched part of the path with the friendly url
                                if (itemUrlMatch.Groups["l"].Success) //if the path had a leading /, then make sure to add that onto the replacement
                                    path = base.EnsureLeadingChar("/", path);

                                /* finish it all off */
                                messages.Add("Item Friendly Url Replacing : " + friendlyUrlPath + " in Path : " + path);

                                //this is the point where the Url is modified!
                                //replace the path in the path - which leaves any other parts of a path intact.
                                friendlyUrlPath = itemUrlRegex.Replace(friendlyUrlPath, path);//replace the part in the friendly Url path with it's replacement.

                                //check if this tab is the one specified to not use a path
                                if (_noDnnPagePathTabId == tab.TabID)
                                    useDnnPagePath = false;//make this Url relative from the site root

                                //set back to default.aspx so that Url Master removes it - just in case it wasn't standard
                                endingPageName = DotNetNuke.Common.Globals.glbDefaultPage;
                            }
                        }
                    }
                }
            }
            return friendlyUrlPath;
        }
        /// <summary>
        /// This method is used by the Url Master Url Rewriting process.  The purpose of this method is to take the supplied array of Url parameters, and transform them into a module-specific querystring for the underlying re-written Url.
        /// </summary>
        /// <param name="urlParms">The array of parameters found after the DNN page path has been identified.  No key/valeu pairs are identified, the parameters are converted from the /key/value/key2/value2 format into [key,value,key2,value2] format.</param>
        /// <param name="tabId">TabId of identified DNN page. </param>
        /// <param name="portalId">PortalId of identified DNN portal.</param>
        /// <param name="options">The current Friendly Url options being used by the module.</param>
        /// <param name="cultureCode">Identified language/culture code, if supplied.</param>
        /// <param name="portalAlias">Identified portalAlias object for the request.</param>
        /// <param name="messages">List of debug messages.  Add to this list to help debug your module.  Can be viewed in the reponse headers of the request, or in the 'Test Url Rewriting' section of the Url Master module.</param>
        /// <param name="status">Out parameter, returns the Http status of the request.  May be 200,301,302, or 404.  For normal rewriting, return a 200 value.</param>
        /// <param name="location">If a 301 or 302 is returned in the status parameter, then this must contain a valid redirect location.  This should be a fully-qualified Url.</param>
        /// <returns>The querystring to be used for rewriting the Url. NOTE: doesn't need to include the tabid if the tabid parameter is > -1</returns>
        public override string TransformFriendlyUrlToQueryString(string[] urlParms, int tabId, int portalId, iFinity.DNN.Modules.UrlMaster.FriendlyUrlOptions options, string cultureCode, DotNetNuke.Entities.Portals.PortalAliasInfo portalAlias, ref List<string> messages, out int status, out string location)
        {
            //store local options variable
            _options = options;
            //initialise results and output variables
            string result = ""; status = 200; //OK 
            location = null; //no redirect location
            if (messages == null) messages = new List<string>();

            //Hashtable queryStringIndex = null;
            //string path = string.Join("/", urlParms);
            //int skipUpToIndex = -1;
            //bool found = false;
            //bool siteRootMatch = false;
            ////look for match on pattern for date and title - the pattern used by this provider
            ////string path = string.Join("/", urlParms);
            ////messages.Add("Checking for Items in Friendly Url path: " + path);
            //if (urlParms.Length > 0)
            //{
            //    //tabid == -1 when no dnn page path is in the Url.  This means the Url Master module can't determine the DNN page based on the Url.
            //    //In this case, it is up to this provider to identify the correct tabId that matches the Url.  Failure to do so will result in the incorrect tab being loaded when the page is rendered. 
            //    if (tabId == -1)
            //    {
            //        siteRootMatch = true;
            //        if (_noDnnPagePathTabId > -1)
            //            //tabid -1 means a 'site root' match - meaning that the dnn page path wasn't included in the Url
            //            tabId = _noDnnPagePathTabId;//if tabid = -1, it means a site root match (no dnn page path) so we substitute in the tabid where this is being used
            //    }
            //    queryStringIndex = UrlController.GetQueryStringIndex(tabId, portalId, this, options, false);
            //    int i = 0;
            //    foreach (string urlParm in urlParms)
            //    {
            //        if (_urlPath != null && _urlPath.ToLower() == urlParm.ToLower())
            //        {
            //            //not this one, will be the next one

            //        }
            //        else
            //        {
            //            //check for existence of this value in the querystring index
            //            string qsKey = urlParm.ToLower();
            //            string qs = (string)queryStringIndex[qsKey];
            //            if (qs != null)
            //            {
            //                //found a querystring match
            //                found = true;
            //                messages.Add("Item Matched in Friendly Url Provider.  Url : " + urlParm + " Path : " + path);
            //                result += qs;
            //                break;
            //            }
            //        }
            //        //if we didn't match, then we will keep this parameter for the output querystring
            //        if (found == false)
            //            skipUpToIndex = i;
            //        i++;
            //    }

            //}

            ////put on any remainder of the path that wasn't to do with the friendly Url
            //string remainder = base.CreateQueryStringFromParameters(urlParms, skipUpToIndex);
            ////put it all together for the final rewrite string
            //result += remainder;

            return result;

        }

        /// <summary>
        /// Determines when to do a redirect.  This is separate to the rewriting process.
        ///   The module developer can create any type of Url redirect here, because the entire Url of the original request is passed in.
        /// </summary>
        /// <param name="tabId">Identified TabId, if known.  -1 if no valid tabid identified.</param>
        /// <param name="portalid">Identified portalId.</param>
        /// <param name="httpAlias">Identified httpAlias of the request.</param>
        /// <param name="requestUri">The original requested Url</param>
        /// <param name="queryStringCol">The querystring collection of the original request</param>
        /// <param name="options">The friendly url options that currently apply.</param>
        /// <param name="redirectLocation">Out parameter that shows where to redirect to.</param>
        /// <param name="messages">List of messages for debug purposes.  Add to this list to help debug your module.</param>
        /// <returns>true if 301 redirect is required, false if not.  If true, the redirectLocation value must be a valid fully qualified Url.</returns>

        public override bool CheckForRedirect(int tabId, int portalid, string httpAlias, Uri requestUri, System.Collections.Specialized.NameValueCollection queryStringCol, iFinity.DNN.Modules.UrlMaster.FriendlyUrlOptions options, out string redirectLocation, ref List<string> messages)
        {
            bool doRedirect = false;
            redirectLocation = "";//set blank location
            //compare to known pattern of old Urls
            Regex groupPathRegex = new Regex(@"/groupid/(?<groupid>\d+)", RegexOptions.IgnoreCase);
            Regex forumPathRegex = new Regex(@"/forumid/(?<forumid>\d+)", RegexOptions.IgnoreCase);
            Regex threadPathRegex = new Regex(@"/threadid/(?<threadid>\d+)", RegexOptions.IgnoreCase);
            Regex postPathRegex = new Regex(@"/postid/(?<postid>\d+)", RegexOptions.IgnoreCase);

            //regex to handle removing the SCOPE parameter from DNNForum urls
            Regex scopePathRegex = new Regex(@"/scope/[^/]+", RegexOptions.IgnoreCase);
            //regex to handle changing the two different page parameters
            Regex threadPagePathRegex = new Regex(@"/threadpage/(?<pageid>\d+)", RegexOptions.IgnoreCase);
            Regex forumPagePathRegex = new Regex(@"/currentpage/(?<pageid>\d+)", RegexOptions.IgnoreCase);


            //Regex to know if we are using a real AF url for editing a post, then we need to NOT replace postId

            Regex ignorePathRegex = new Regex(@"/afv/post/action/[^/]+", RegexOptions.IgnoreCase);

            string path = requestUri.AbsoluteUri;

            redirectLocation = path;

            var ignoreMatch = ignorePathRegex.Match(redirectLocation);
            var postMatch = postPathRegex.Match(redirectLocation);
            //check for an existing PostId from DNNForum (direct link to a post)
            if (postMatch.Success && !ignoreMatch.Success)
            {
                //todo: should ignore ForumId in the original URL if we match a postid? 
                string postid = postMatch.Groups["postid"].Value;
                int itemId;
                if (int.TryParse(postid, out itemId))
                {
                    //ok, valid item Id found
                    //get the valid Url for this item
                    Hashtable friendlyUrlIndex = UrlController.GetFriendlyUrlIndex(tabId, portalid, this, options);
                    //look up the friendly url index using the item key
                    string furlKey = "replyi" + postid;
                    if (friendlyUrlIndex != null)
                    {
                        string friendlyUrl = (string)friendlyUrlIndex[furlKey];
                        if (friendlyUrl != null)
                        {
                            //ok, we're going to replace this in the Url
                            friendlyUrl = base.EnsureLeadingChar("/", friendlyUrl);
                            string result = postPathRegex.Replace(redirectLocation, friendlyUrl);
                            //remove ForumID from the parameters cause we don't need them anymore with a targetted postid
                            result = forumPathRegex.Replace(result, string.Empty);
                            doRedirect = true;
                            redirectLocation = result;
                        }
                        //if we didn't find the URL it likely means we are on the FIRST post so use aft parameters
                        else
                        {
                            furlKey = "threadi" + postid;

                            friendlyUrl = (string)friendlyUrlIndex[furlKey];
                            if (friendlyUrl != null)
                            {
                                //ok, we're going to replace this in the Url
                                friendlyUrl = base.EnsureLeadingChar("/", friendlyUrl);
                                string result = postPathRegex.Replace(redirectLocation, friendlyUrl);
                                result = forumPathRegex.Replace(result, string.Empty);
                                doRedirect = true;
                                redirectLocation = result;
                            }
                        }
                    }
                }
            }


            var threadMatch = threadPathRegex.Match(redirectLocation);

            //check for an existing threadid from DNNForum
            if (threadMatch.Success)
            {
                string threadid = threadMatch.Groups["threadid"].Value;
                int itemId;
                if (int.TryParse(threadid, out itemId))
                {
                    //ok, valid item Id found
                    //get the valid Url for this item
                    Hashtable friendlyUrlIndex = UrlController.GetFriendlyUrlIndex(tabId, portalid, this, options);
                    //look up the friendly url index using the item key
                    string furlKey = "threadi" + threadid;
                    if (friendlyUrlIndex != null)
                    {
                        string friendlyUrl = (string)friendlyUrlIndex[furlKey];
                        if (friendlyUrl != null)
                        {
                            //ok, we're going to replace this in the Url
                            friendlyUrl = base.EnsureLeadingChar("/", friendlyUrl);
                            string result = threadPathRegex.Replace(redirectLocation, friendlyUrl);
                            doRedirect = true;
                            redirectLocation = result;
                        }
                    }
                }
            }


            var groupMatch = groupPathRegex.Match(redirectLocation);

            //check for groupId from DNNForum
            if (groupMatch.Success)
            {
                string groupid = groupMatch.Groups["groupid"].Value;
                int itemId;
                if (int.TryParse(groupid, out itemId))
                {
                    //ok, valid item Id found
                    //get the valid Url for this item
                    Hashtable friendlyUrlIndex = UrlController.GetFriendlyUrlIndex(tabId, portalid, this, options);
                    //look up the friendly url index using the item key
                    string furlKey = "groupi" + groupid;
                    if (friendlyUrlIndex != null)
                    {
                        string friendlyUrl = (string)friendlyUrlIndex[furlKey];
                        if (friendlyUrl != null)
                        {
                            //ok, we're going to replace this in the Url
                            friendlyUrl = base.EnsureLeadingChar("/", friendlyUrl);
                            string result = groupPathRegex.Replace(redirectLocation, friendlyUrl);
                            doRedirect = true;
                            redirectLocation = result;
                        }
                    }
                }
            }

            var forumMatch = forumPathRegex.Match(redirectLocation);

            //check for a ForumID from DNNForum
            if (forumMatch.Success)
            {
                string forumid = forumMatch.Groups["forumid"].Value;
                int itemId;
                if (int.TryParse(forumid, out itemId))
                {
                    //ok, valid item Id found
                    //get the valid Url for this item
                    Hashtable friendlyUrlIndex = UrlController.GetFriendlyUrlIndex(tabId, portalid, this, options);
                    //look up the friendly url index using the item key
                    string furlKey = "forumi" + forumid;
                    if (friendlyUrlIndex != null)
                    {
                        string friendlyUrl = (string)friendlyUrlIndex[furlKey];
                        if (friendlyUrl != null)
                        {
                            //ok, we're going to replace this in the Url
                            friendlyUrl = base.EnsureLeadingChar("/", friendlyUrl);
                            string result = forumPathRegex.Replace(redirectLocation, friendlyUrl);
                            doRedirect = true;
                            redirectLocation = result;
                        }
                    }
                }
            }



            var forumPageMatch = forumPagePathRegex.Match(redirectLocation);

            //check for currentpage from DNNForum
            if (forumPageMatch.Success)
            {
                string pageId = forumPageMatch.Groups["pageid"].Value;
                int newId;
                if (int.TryParse(pageId, out newId))
                {
                    //ok, valid Id found
                    string newPageParam = base.EnsureLeadingChar("/", "afgp/" + newId.ToString());
                    string result = forumPagePathRegex.Replace(redirectLocation, newPageParam);
                    doRedirect = true;
                    redirectLocation = result;

                }
            }

            var threadPageMatch = threadPagePathRegex.Match(redirectLocation);

            //check for threadpage from DNNForum
            if (threadPageMatch.Success)
            {
                string pageId = threadPageMatch.Groups["pageid"].Value;
                int newId;
                if (int.TryParse(pageId, out newId))
                {
                    //ok, valid Id found
                    string newPageParam = base.EnsureLeadingChar("/", "afgp/" + newId.ToString());
                    string result = threadPagePathRegex.Replace(redirectLocation, newPageParam);
                    doRedirect = true;
                    redirectLocation = result;

                }
            }
            var scopePageMatch = scopePathRegex.Match(redirectLocation);
            //clean out all "scope" parameters from DNN Forum urls
            if (scopePageMatch.Success)
            {
                string result = scopePathRegex.Replace(redirectLocation, string.Empty);
                doRedirect = true;
                redirectLocation = result;
            }



            return doRedirect;
        }

        public override string FriendlyName
        {
            get { return "DotNetNuke ActiveForums Friendly Url Provider"; }
        }
        /// <summary>
        /// Returns any custom settings that are specific per-portal for this instance
        /// </summary>
        /// <remarks>
        /// This is used to write the values back out to the web.config from the Url Master UI
        /// </remarks>
        /// <returns>A Dictionary of the key/value pairs of the settings used in this provider.  Return empty dictionary if no portal specific options.</returns>
        public override Dictionary<string, string> GetProviderPortalSettings()
        {
            //returns the settings specific to this portal instance
            Dictionary<string, string> settings = new Dictionary<string, string>();
            if (_urlPath != null && _urlPath != "")
                settings.Add("urlPath", _urlPath);
            if (_noDnnPagePathTabId > 0)
                settings.Add("noDnnPagePathTabId", _noDnnPagePathTabId.ToString());
            return settings;
        }

        public override bool AlwaysUsesDnnPagePath(int portalId)
        {
            if (_noDnnPagePathTabId > -1)
            {
                return false;//if there is an exception, then return false
            }
            else
                return true;//no specific exceptions, return true every time
        }
        public override bool IsLicensed(Uri requestUri, out string messageHtml, out string debugMessage)
        {
            //If this module had a licensing requirement, it would be checked here.  If not licensed
            //return false, and return some Html to be included on any pages where the provider is used, ie:
            //messageHtml = "<div>Hey! this isn't licensed!</div>"; debugMessage = "Fake licence message";
            //return false;

            //but in this case, there's no licensing restrictions with this provider, so always return true
            //and return nothing for the messagehtml and debugmessage
            messageHtml = null; debugMessage = null;
            return true;
        }
        /// <summary>
        /// Returns the Path of the Settings .ascx control (if supplied).  The Settings control is loaded by the Portal Urls page for the provider,
        /// and allows interaction of the settings by the end user, at a per-portal level.
        /// </summary>
        /// <remarks>
        /// Return empty or null string if no control exists.  The path should match the path specified in the DNN install manifest, and 
        /// point to an actual file.
        /// </remarks>
        public override string SettingsControlSrc
        {
            get { return "DesktopModules/DotNetNuke.ActiveForumsFriendlyUrlProvider/Settings.ascx"; }
        }

        #endregion
        #region internal methods and properties
        internal new string CleanNameForUrl(string title, FriendlyUrlOptions options)
        {
            bool replaced = false;
            //the base module Url PRovider contains a Url cleaning routine, which will remove illegal and unwanted characters from a string, using the specific friendly url options
            return base.CleanNameForUrl(title, options, out replaced);
        }
        #endregion

        internal int NoDnnPagePathTabId
        {
            get { return _noDnnPagePathTabId; }
            set { _noDnnPagePathTabId = value; }
        }

        internal string UrlPath
        {
            get { return _urlPath; }
            set { _urlPath = value; }
        }
    }
}
